package com.studentgrowth.service.learning;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.studentgrowth.dto.learningplan.*;
import com.studentgrowth.model.learning.LearningPlan;
import com.studentgrowth.repository.LearningPlanRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.time.LocalDate;
import java.util.*;

@Service
public class LearningPlanService {
    
    @Autowired
    private LearningPlanRepository learningPlanRepository;
    
    @Autowired
    private ObjectMapper objectMapper;

    // 课程数据
    private static final Map<String, CourseInfo> COURSE_MAP = new HashMap<String, CourseInfo>() {{
        put("java", new CourseInfo(
            "Java Language",
            "intermediate",
            Arrays.asList(
                "Java基础语法",
                "面向对象编程",
                "集合框架",
                "多线程编程",
                "IO与网络编程",
                "Spring框架基础",
                "数据库编程"
            )
        ));
        
        put("python", new CourseInfo(
            "Python Programming",
            "basic",
            Arrays.asList(
                "Python基础语法",
                "数据类型与结构",
                "函数与模块",
                "面向对象编程",
                "文件操作与异常处理",
                "数据分析基础",
                "Web开发入门"
            )
        ));
        
        put("algo", new CourseInfo(
            "Algorithm Design",
            "advanced",
            Arrays.asList(
                "算法复杂度分析",
                "排序算法",
                "查找算法",
                "动态规划",
                "贪心算法",
                "图论算法",
                "高级数据结构"
            )
        ));
        
        put("ds", new CourseInfo(
            "Data Structures",
            "intermediate",
            Arrays.asList(
                "数组与字符串",
                "链表",
                "栈与队列",
                "树与二叉树",
                "图结构",
                "散列表",
                "高级树结构"
            )
        ));
        
        put("ml", new CourseInfo(
            "Machine Learning",
            "advanced",
            Arrays.asList(
                "机器学习基础",
                "监督学习",
                "非监督学习",
                "深度学习基础",
                "神经网络",
                "模型评估与优化",
                "实战项目"
            )
        ));
    }};

    // 课程信息内部类
    private static class CourseInfo {
        String name;
        String difficulty;
        List<String> topics;

        CourseInfo(String name, String difficulty, List<String> topics) {
            this.name = name;
            this.difficulty = difficulty;
            this.topics = topics;
        }
    }

    public LearningPlanResponse generatePlan(QuestionnaireRequest request, Long userId) {
        // 1. 保存学习计划基本信息
        LearningPlan plan = new LearningPlan();
        plan.setUserId(userId);
        plan.setLearningPeriod(request.getLearningPeriod());
        plan.setDailyDuration(request.getStudyDuration());
        try {
            plan.setSelectedCourses(objectMapper.writeValueAsString(request.getSelectedCourses()));
            plan.setLearningGoals(objectMapper.writeValueAsString(request.getLearningGoals()));
        } catch (Exception e) {
            throw new RuntimeException("JSON序列化失败", e);
        }
        plan.setCreateTime(LocalDateTime.now());
        plan.setUpdateTime(LocalDateTime.now());
        
        // 使用MyBatis-Plus的insert方法
        learningPlanRepository.insert(plan);

        // 2. 生成课程安排
        List<CourseSchedule> courseSchedules = generateCourseSchedules(request);

        // 3. 生成每日时间安排
        DailySchedule dailySchedule = generateDailySchedule(request.getStudyDuration());

        // 4. 生成里程碑
        List<Milestone> milestones = generateMilestones(request);

        // 5. 构建响应
        LearningPlanResponse response = new LearningPlanResponse();
        response.setPlanId(plan.getId());
        response.setCourseSchedules(courseSchedules);
        response.setDailySchedule(dailySchedule);
        response.setMilestones(milestones);

        return response;
    }

    private List<CourseSchedule> generateCourseSchedules(QuestionnaireRequest request) {
        List<CourseSchedule> schedules = new ArrayList<>();
        
        // 获取学习周期（月）
        int months = Integer.parseInt(request.getLearningPeriod().split(" ")[0]);
        int totalWeeks = months * 4;
        
        // 计算每周总学习时间（小时）
        int weeklyTotalHours = (request.getStudyDuration() * 7) / 60;
        
        // 为每个选中的课程分配时间
        int coursesCount = request.getSelectedCourses().size();
        int averageHoursPerCourse = weeklyTotalHours / coursesCount;

        for (String courseId : request.getSelectedCourses()) {
            CourseInfo courseInfo = COURSE_MAP.get(courseId);
            if (courseInfo != null) {
                CourseSchedule schedule = new CourseSchedule();
                schedule.setCourseId(courseId);
                schedule.setCourseName(courseInfo.name);
                schedule.setWeeklyHours(averageHoursPerCourse);
                schedule.setTopics(courseInfo.topics);
                schedules.add(schedule);
            }
        }

        return schedules;
    }

    private DailySchedule generateDailySchedule(Integer dailyMinutes) {
        DailySchedule schedule = new DailySchedule();
        schedule.setDailyDuration(dailyMinutes);
        
        List<TimeSlot> timeSlots = new ArrayList<>();
        
        // 根据每日学习时长生成时间段建议
        if (dailyMinutes <= 60) {
            // 短时学习：一次完成
            timeSlots.add(new TimeSlot("19:00", "20:00", "集中学习时间"));
        } else if (dailyMinutes <= 120) {
            // 中等时长：分两次
            timeSlots.add(new TimeSlot("12:00", "13:00", "午休学习时间"));
            timeSlots.add(new TimeSlot("19:00", "20:00", "晚间学习时间"));
        } else {
            // 长时学习：分三次
            timeSlots.add(new TimeSlot("08:00", "09:00", "晨间学习时间"));
            timeSlots.add(new TimeSlot("12:00", "13:00", "午休学习时间"));
            timeSlots.add(new TimeSlot("19:00", "21:00", "晚间学习时间"));
        }
        
        schedule.setTimeSlots(timeSlots);
        return schedule;
    }

    private List<Milestone> generateMilestones(QuestionnaireRequest request) {
        List<Milestone> milestones = new ArrayList<>();
        LocalDate startDate = LocalDate.now();
        
        // 解析学习周期
        int months = Integer.parseInt(request.getLearningPeriod().split(" ")[0]);
        
        // 为每个选中的课程生成里程碑
        for (String courseId : request.getSelectedCourses()) {
            CourseInfo courseInfo = COURSE_MAP.get(courseId);
            if (courseInfo != null) {
                // 第一个月里程碑
                Milestone milestone1 = new Milestone();
                milestone1.setTitle(courseInfo.name + " 基础掌握");
                milestone1.setTargetDate(startDate.plusMonths(1));
                milestone1.setDescription("完成" + courseInfo.name + "基础概念学习");
                milestones.add(milestone1);
                
                // 中期里程碑
                if (months > 2) {
                    Milestone milestone2 = new Milestone();
                    milestone2.setTitle(courseInfo.name + " 进阶应用");
                    milestone2.setTargetDate(startDate.plusMonths(months / 2));
                    milestone2.setDescription("完成" + courseInfo.name + "进阶主题学习并进行实践");
                    milestones.add(milestone2);
                }
                
                // 最终里程碑
                Milestone milestone3 = new Milestone();
                milestone3.setTitle(courseInfo.name + " 高级掌握");
                milestone3.setTargetDate(startDate.plusMonths(months));
                milestone3.setDescription("完成" + courseInfo.name + "高级特性学习并完成项目实践");
                milestones.add(milestone3);
            }
        }
        
        return milestones;
    }
} 